#!/usr/bin/python
# -*- coding: utf-8 -*-
# @name             : 数据库基本操作
# @author           : OneYoung
# @create           : 2024/02/04
# @version          : v1.0
# @desc             :

import pymysql
import psycopg2
import cx_Oracle
from utils.log_record import logger
from application.settings import DB_TYPE, DB_CONFIG


class DBGetter:
    """ 数据库基本配置 """

    def __init__(self):
        self.db = None

    @classmethod
    def db_connect(cls, db_name=None):
        """
        创建数据库连接
        :param db_name: 数据库名称
        :return:
        """
        DB_CONFIG['database'] = db_name if db_name else DB_CONFIG['database']
        db_type = DB_TYPE.upper()
        if db_type == 'POSTGRESQL':
            cls.db = psycopg2.connect(**DB_CONFIG)
        elif db_type == 'MYSQL':
            cls.db = pymysql.connect(**DB_CONFIG)
        elif db_type == 'ORACLE':
            cls.db = cx_Oracle.connect(
                DB_CONFIG['user'],
                DB_CONFIG['password'],
                f"{DB_CONFIG['host']}:{DB_CONFIG['port']}/{DB_CONFIG['database']}"
            )
        else:
            raise f'不支持的数据库类型{DB_TYPE}，请根据需要自行配置!'

    @classmethod
    def execute_sql(cls, sql: str, database: str = None):
        """
        执行SQL
        :param sql: 执行SQL语句
        :param database: 数据库名称
        :return:
        """

        try:
            cls.db_connect(database)  # 连接数据库
            print("数据库连接成功.")
            try:
                cursor = cls.db.cursor()  # 获取游标
                cursor.execute(sql)  # 执行sql
                cls.db.commit()  # 提交到数据库执行
                return cursor
            except Exception as rc:
                logger.error(f"SQL执行失败.{rc}")
            finally:
                cls.db.close()
                print("关闭数据库连接.")
        except Exception as ec:
            msg = f"数据库连接失败.{ec}"
            logger.error(msg)
            raise ConnectionError(msg)

    @classmethod
    def get_first_result(cls, sql: str, database: str = None):
        """
        获取第一条查询结果
        :param database: 数据库名称
        :param sql: 执行SQL语句
        :return:
        """
        cursor = cls.execute_sql(database, sql)
        if cursor:
            result = cursor.fetchone()
            return result
        return None

    @classmethod
    def get_all_result(cls, sql: str, database: str = None):
        """
        获取所有查询结果
        :param database: 数据库名称
        :param sql: 执行SQL语句
        :return:
        """
        cursor = cls.execute_sql(database, sql)
        if cursor:
            results = cursor.fetchall()
            return results
        return None
